package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 通过这个类来实现一些后端提供的接口
 */

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BlogDao blogDao = new BlogDao();
        String blogId = req.getParameter("blogId");
        if (blogId == null){
            List<Blog> blogs = blogDao.selectAll();
            String respString = objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respString);
        }else{
            Blog blog = blogDao.selectOne(Integer.valueOf(blogId));
            String respString = objectMapper.writeValueAsString(blog);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respString);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        //System.out.println(blogId);
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if (title == null || title.equals("") || content == null || content.equals("")){
            String html = "<h3>title 或者 content 为空，获取博客失败</h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }

        HttpSession session = req.getSession(false);
        if (session == null) {
            String html = "<h3>当前用户未登录! 新增博客失败!</h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            String html = "<h3>当前用户未登录! 新增博客失败!</h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        Blog blog = new Blog();
        blog.setUserId(user.getUserId());
        blog.setTitle(title);
        blog.setContent(content);
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));

        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);

//        ///////////////////////////////////////////////////////////
//        // 1. 写一个工具类将 title 能和时间作比较，计算时间差
//        //String time = “2018-10-28”;
//        Date date = new Date();
//        //String blogId = req.getParameter("blogId");
//        try {
//            SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            date = formatter.parse(title);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        // 2. 计算完时间差之后，就将这个 task 放到定时器里面，执行的业务就是转换数据库中博客的userId
//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                //BlogDao blogDao = new BlogDao();
//                System.out.println(title);
//                int blogId = blogDao.selectByTile(title).getBlogId();
//                blogDao.update(blogId);
//            }
//        }, date.getTime() - System.currentTimeMillis());
//        ///////////////////////////////////////////////////////////
        resp.sendRedirect("blog_list.html");
    }
}
